package com.hosever.action;

import java.util.ArrayList;
import java.util.List;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

/**
 * gson模板 需要引入gson.jar
 * 
 * @author Sever
 * 
 */
public class GsonDemo {

	public static String createJsonString(Object value) {
		Gson gson = new Gson();
		String str = gson.toJson(value);
		return str;
	}

	public static <T> T getEntity(String jsonString, Class<T> cls) {
		T t = null;
		try {
			Gson gson = new Gson();
			t = gson.fromJson(jsonString, cls);
		} catch (Exception e) {
			// TODO: handle exception
		}
		return t;
	}
	public static <T> List<T> getEntities(String jsonString, Class<T> cls) {
        List<T> list = new ArrayList<T>();
        try {
            Gson gson = new Gson();
            list = gson.fromJson(jsonString, new TypeToken<List<T>>() {
            }.getType());
        } catch (Exception e) {
        }
        return list;
    }

	public static void main(String[] args) {
		FatYo fy = new FatYo();
		String jsonString = GsonDemo.createJsonString(fy);
		System.out.println("【java实体转化json字符串】"+jsonString);
		FatYo fy2  = GsonDemo.getEntity(jsonString, fy.getClass());
		System.out.println("【json字符串转化java实体】"+fy2+fy2.getOriginalName());
		
		
	}
}



